home *** CD-ROM | disk | FTP | other *** search
/ Mac Easy 2010 May / Mac Life Ubuntu.iso / casper / filesystem.squashfs / var / lib / python-support / python2.6 / rdflib / sparql / graphPattern.pyc (.txt) < prev    next >
Encoding:
Python Compiled Bytecode  |  2009-04-20  |  14.9 KB  |  392 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.6)
  3.  
  4. '''
  5. Graph pattern class used by the SPARQL implementation
  6. '''
  7. import sys
  8. import os
  9. import time
  10. import datetime
  11. from rdflib.Literal import Literal
  12. from rdflib.BNode import BNode
  13. from rdflib.URIRef import URIRef
  14. from types import *
  15. from rdflib.sparql import _questChar, Debug, SPARQLError
  16. from rdflib.sparql.Unbound import Unbound
  17.  
  18. def _createResource(v):
  19.     """Create an RDFLib Literal instance with the corresponding XML
  20.     Schema datatype set. If the variable is already an RDFLib
  21.     resource, it simply returns the resource; otherwise the
  22.     corresponding Literal.  A SPARQLError Exception is raised if the
  23.     type is not implemented.
  24.  
  25.     The Literal contains the string representation of the variable (as
  26.     Python does it by default) with the corresponding XML Schema URI
  27.     set.
  28.  
  29.     @param v: Python variable
  30.     @return: either an RDFLib Literal (if 'v' is not an RDFLib Resource), or the same variable if it is already
  31.     an RDFLib resource (ie, Literal, BNode, or URIRef)
  32.     @raise SPARQLError: if the type of 'v' is not implemented
  33.     """
  34.     if isinstance(v, Literal) and isinstance(v, BNode) or isinstance(v, URIRef):
  35.         return v
  36.     return Literal(v)
  37.  
  38.  
  39. def _isResQuest(r):
  40.     '''
  41.     Is \'r\' a request string (ie, of the form "?XXX")?
  42.  
  43.     @rtype: Boolean
  44.     '''
  45.     if r and isinstance(r, basestring) and r[0] == _questChar:
  46.         return True
  47.     return False
  48.  
  49.  
  50. class GraphPattern:
  51.     '''
  52.     Storage of one Graph Pattern, ie, the pattern tuples and the
  53.     possible (functional) constraints (filters)
  54.     '''
  55.     
  56.     def __init__(self, patterns = []):
  57.         '''
  58.         @param patterns: an initial list of graph pattern tuples
  59.         '''
  60.         self.patterns = []
  61.         self.constraints = []
  62.         self.unbounds = []
  63.         self.bnodes = { }
  64.         if type(patterns) == list:
  65.             self.addPatterns(patterns)
  66.         elif type(patterns) == tuple:
  67.             self.addPattern(patterns)
  68.         else:
  69.             raise SPARQLError('illegal argument, pattern must be a tuple or a list of tuples')
  70.         return type(patterns) == list
  71.  
  72.     
  73.     def _generatePattern(self, tupl):
  74.         """
  75.         Append a tuple to the local patterns. Possible type literals
  76.         are converted to real literals on the fly.  Each tuple should
  77.         be contain either 3 elements (for an RDF Triplet pattern) or
  78.         four, where the fourth element is a per-pattern constraint
  79.         (filter). (The general constraint of SPARQL can be optimized
  80.         by assigning a constraint to a specific pattern; because it
  81.         stops the graph expansion, its usage might be much more
  82.         optimal than the the 'global' constraint).
  83.  
  84.         @param tupl: either a three or four element tuple
  85.         """
  86.         if type(tupl) != tuple:
  87.             raise SPARQLError('illegal argument, pattern must be a tuple, got %s' % type(tupl))
  88.         type(tupl) != tuple
  89.         if len(tupl) != 3 and len(tupl) != 4:
  90.             raise SPARQLError('illegal argument, pattern must be a tuple of 3 or 4 element, got %s' % len(tupl))
  91.         len(tupl) != 4
  92.         if len(tupl) == 3:
  93.             (s, p, o) = tupl
  94.             f = None
  95.         else:
  96.             (s, p, o, f) = tupl
  97.         final = []
  98.         for c in (s, p, o):
  99.             if _isResQuest(c):
  100.                 if c not in self.unbounds:
  101.                     self.unbounds.append(c)
  102.                 
  103.                 final.append(c)
  104.                 continue
  105.             if isinstance(c, BNode):
  106.                 final.append(c)
  107.                 continue
  108.             final.append(_createResource(c))
  109.         
  110.         final.append(f)
  111.         return tuple(final)
  112.  
  113.     
  114.     def addPattern(self, tupl):
  115.         """
  116.         Append a tuple to the local patterns. Possible type literals
  117.         are converted to real literals on the fly.  Each tuple should
  118.         be contain either 3 elements (for an RDF Triplet pattern) or
  119.         four, where the fourth element is a per-pattern constraint
  120.         (filter). (The general constraint of SPARQL can be optimized
  121.         by assigning a constraint to a specific pattern; because it
  122.         stops the graph expansion, its usage might be much more
  123.         optimal than the the 'global' constraint).
  124.  
  125.         @param tupl: either a three or four element tuple
  126.         """
  127.         self.patterns.append(self._generatePattern(tupl))
  128.  
  129.     
  130.     def insertPattern(self, tupl):
  131.         """
  132.         Insert a tuple to to the start of local patterns. Possible
  133.         type literals are converted to real literals on the fly.  Each
  134.         tuple should be contain either 3 elements (for an RDF Triplet
  135.         pattern) or four, where the fourth element is a per-pattern
  136.         constraint (filter). (The general constraint of SPARQL can be
  137.         optimized by assigning a constraint to a specific pattern;
  138.         because it stops the graph expansion, its usage might be much
  139.         more optimal than the the 'global' constraint).
  140.  
  141.         Semantically, the behaviour induced by a graphPattern does not
  142.         depend on the order of the patterns. However, due to the
  143.         behaviour of the expansion algorithm, users may control the
  144.         speed somewhat by adding patterns that would 'cut' the
  145.         expansion tree soon (ie, patterns that reduce the available
  146.         triplets significantly). API users may be able to do that,
  147.         hence this additional method.
  148.  
  149.         @param tupl: either a three or four element tuple
  150.         """
  151.         self.patterns.insert(0, self._generatePattern(tupl))
  152.  
  153.     
  154.     def addPatterns(self, lst):
  155.         """
  156.         Append a list of tuples to the local patterns. Possible type
  157.         literals are converted to real literals on the fly.  Each
  158.         tuple should be contain either three elements (for an RDF
  159.         Triplet pattern) or four, where the fourth element is a
  160.         per-pattern constraint. (The general constraint of SPARQL can
  161.         be optimized by assigning a constraint to a specific pattern;
  162.         because it stops the graph expansion, its usage might be much
  163.         more optimal than the the 'global' constraint).
  164.  
  165.         @param lst: list consisting of either a three or four element tuples
  166.         """
  167.         for l in lst:
  168.             self.addPattern(l)
  169.         
  170.  
  171.     
  172.     def insertPatterns(self, lst):
  173.         """
  174.         Insert a list of tuples to the start of the local
  175.         patterns. Possible type literals are converted to real
  176.         literals on the fly.  Each tuple should be contain either
  177.         three elements (for an RDF Triplet pattern) or four, where the
  178.         fourth element is a per-pattern constraint. (The general
  179.         constraint of SPARQL can be optimized by assigning a
  180.         constraint to a specific pattern; because it stops the graph
  181.         expansion, its usage might be much more optimal than the the
  182.         'global' constraint).
  183.  
  184.         Semantically, the behaviour induced by a graphPattern does not
  185.         depend on the order of the patterns. However, due to the
  186.         behaviour of the expansion algorithm, users may control the
  187.         speed somewhat by adding patterns that would 'cut' the
  188.         expansion tree soon (ie, patterns that reduce the available
  189.         triplets significantly). API users may be able to do that,
  190.         hence this additional method.
  191.  
  192.         @param lst: list consisting of either a three or four element tuples
  193.         """
  194.         for i in xrange(len(lst) - 1, -1, -1):
  195.             self.insertPattern(lst[i])
  196.         
  197.  
  198.     
  199.     def addConstraint(self, func):
  200.         """
  201.         Add a global filter constraint to the graph pattern. 'func'
  202.         must be a method with a single input parameter (a dictionary)
  203.         returning a boolean. This method is I{added} to previously
  204.         added methods, ie, I{all} methods must return True to accept a
  205.         binding.
  206.  
  207.         @param func: filter function
  208.         """
  209.         if type(func) == FunctionType:
  210.             self.constraints.append(func)
  211.         else:
  212.             raise SPARQLError('illegal argument, constraint must be a function type, got %s' % type(func))
  213.         return type(func) == FunctionType
  214.  
  215.     
  216.     def addConstraints(self, lst):
  217.         '''
  218.         Add a list of global filter constraints to the graph
  219.         pattern. Each function in the list must be a method with a
  220.         single input parameter (a dictionary) returning a
  221.         boolean. These methods are I{added} to previously added
  222.         methods, ie, I{all} methods must return True to accept a
  223.         binding.
  224.  
  225.         @param lst: list of functions
  226.         '''
  227.         for l in lst:
  228.             self.addConstraint(l)
  229.         
  230.  
  231.     
  232.     def construct(self, tripleStore, bindings):
  233.         '''
  234.         Add triples to a tripleStore based on a variable bindings of
  235.         the patterns stored locally.  The triples are patterned by the
  236.         current Graph Pattern. The method is used to construct a graph
  237.         after a successful querying.
  238.  
  239.         @param tripleStore: an (rdflib) Triple Store
  240.         @param bindings: dictionary
  241.         '''
  242.         localBnodes = { }
  243.         for c in self.bnodes:
  244.             localBnodes[c] = BNode()
  245.         
  246.         
  247.         def bind(st):
  248.             if _isResQuest(st):
  249.                 if st in bindings:
  250.                     return bindings[st]
  251.                 if isinstance(self, GraphPattern2):
  252.                     return st
  253.                 return None
  254.             _isResQuest(st)
  255.             if isinstance(st, BNode):
  256.                 for c in self.bnodes:
  257.                     if self.bnodes[c] == st:
  258.                         return localBnodes[c]
  259.                 
  260.                 return st
  261.             return st
  262.  
  263.         for pattern in self.patterns:
  264.             (s, p, o, f) = pattern
  265.             triplet = []
  266.             valid = True
  267.             for res in (s, p, o):
  268.                 val = bind(res)
  269.                 if val != None:
  270.                     triplet.append(val)
  271.                     continue
  272.                 (None, None, None)
  273.                 valid = False
  274.             
  275.             if valid:
  276.                 tripleStore.add(tuple(triplet))
  277.                 continue
  278.         
  279.  
  280.     
  281.     def __add__(self, other):
  282.         '''Adding means concatenating all the patterns and filters arrays'''
  283.         retval = GraphPattern()
  284.         retval += self
  285.         retval += other
  286.         return retval
  287.  
  288.     
  289.     def __iadd__(self, other):
  290.         '''Adding means concatenating all the patterns and filters arrays'''
  291.         self.patterns += other.patterns
  292.         self.constraints += other.constraints
  293.         for c in other.unbounds:
  294.             if c not in self.unbounds:
  295.                 self.unbounds.append(c)
  296.                 continue
  297.             self
  298.         
  299.         for c in other.bnodes:
  300.             if c not in self.bnodes:
  301.                 self.bnodes[c] = other.bnodes[c]
  302.                 continue
  303.             self
  304.         
  305.         return self
  306.  
  307.     
  308.     def __repr__(self):
  309.         retval = '   Patterns:    %s\n' % self.patterns
  310.         retval += '   Constraints: %s\n' % self.constraints
  311.         retval += '   Unbounds:    %s\n' % self.unbounds
  312.         return retval
  313.  
  314.     
  315.     def __str__(self):
  316.         return self.__repr__()
  317.  
  318.     
  319.     def isEmpty(self):
  320.         '''Is the pattern empty?
  321.         @rtype: Boolean
  322.         '''
  323.         return len(self.patterns) == 0
  324.  
  325.  
  326.  
  327. class BasicGraphPattern(GraphPattern):
  328.     '''One, justified, problem with the current definition of L{GraphPattern<GraphPattern>} is that it
  329.     makes it difficult for users to use a literal of the type "?XXX", because any string beginning
  330.     with "?" will be considered to be an unbound variable. The only way of doing this is that the user
  331.     explicitly creates a Literal object and uses that as part of the pattern.
  332.  
  333.     This class is a superclass of L{GraphPattern<GraphPattern>} which does I{not} do this, but requires the
  334.     usage of a separate variable class instance'''
  335.     
  336.     def __init__(self, patterns = []):
  337.         '''
  338.         @param patterns: an initial list of graph pattern tuples
  339.         '''
  340.         GraphPattern.__init__(self, patterns)
  341.  
  342.     
  343.     def _generatePattern(self, tupl):
  344.         """
  345.         Append a tuple to the local patterns. Possible type literals
  346.         are converted to real literals on the fly.  Each tuple should
  347.         be contain either 3 elements (for an RDF Triplet pattern) or
  348.         four, where the fourth element is a per-pattern constraint
  349.         (filter). (The general constraint of SPARQL can be optimized
  350.         by assigning a constraint to a specific pattern; because it
  351.         stops the graph expansion, its usage might be much more
  352.         optimal than the the 'global' constraint).
  353.  
  354.         @param tupl: either a three or four element tuple
  355.         """
  356.         if type(tupl) != tuple:
  357.             raise SPARQLError('illegal argument, pattern must be a tuple, got %s' % type(tupl))
  358.         type(tupl) != tuple
  359.         if len(tupl) != 3 and len(tupl) != 4:
  360.             raise SPARQLError('illegal argument, pattern must be a tuple of 3 or 4 element, got %s' % len(tupl))
  361.         len(tupl) != 4
  362.         if len(tupl) == 3:
  363.             (s, p, o) = tupl
  364.             f = None
  365.         else:
  366.             (s, p, o, f) = tupl
  367.         final = []
  368.         for c in (s, p, o):
  369.             if isinstance(c, Unbound):
  370.                 if c.name not in self.unbounds:
  371.                     self.unbounds.append(c.name)
  372.                 
  373.                 final.append(c.name)
  374.                 continue
  375.             if isinstance(c, BNode):
  376.                 final.append(c)
  377.                 continue
  378.             final.append(_createResource(c))
  379.         
  380.         final.append(f)
  381.         return tuple(final)
  382.  
  383.  
  384. if __name__ == '__main__':
  385.     v1 = Unbound('a')
  386.     g = BasicGraphPattern([
  387.         ('a', '?b', 24),
  388.         ('?r', '?c', 12345),
  389.         (v1, '?c', 3333)])
  390.     print g
  391.  
  392.